package cn.kmia.hrm.service.system;

import cn.kmia.hrm.pojo.system.RolePermission;
import cn.kmia.hrm.service.BaseService;
import org.nutz.aop.interceptor.ioc.TransAop;
import org.nutz.dao.Sqls;
import org.nutz.dao.sql.Sql;
import org.nutz.ioc.aop.Aop;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.log.Log;
import org.nutz.log.Logs;

import java.sql.Timestamp;
import java.util.Date;

/**
 * @项目：java_baggage_led
 * @作者：4K
 * @描述：角色对应权限信息
 * @日期：created in 9:32 2018/3/5
 */
@IocBean
public class RolePermissionService extends BaseService {

    private static final Log log = Logs.get();

    /**
     * 设置
     *
     * @param rolePers UserRole[] 角色权限信息
     * @param idcard    String  操作人
     * @return
     */
    @Aop(TransAop.READ_COMMITTED)
    public void edit(RolePermission[] rolePers, String idcard) throws Exception {
        if (rolePers != null) {
            try {
                String roleIds = "";
                for (RolePermission rolePermission : rolePers) {
                    roleIds += "," + rolePermission.getRoleId();
                }
                // 删除原有角色权限
                if (!roleIds.equals("")) {
                    roleIds = roleIds.substring(1);
                    Sql sql = Sqls.create("delete from sys_role_permission where role_id in (" + roleIds + ")");
                    dao.execute(sql);
                }
                // 新增角色权限
                for (int i = 0; i < rolePers.length; i++) {
                    rolePers[i].setOpBy(idcard);
                    rolePers[i].setUpdateTime(new Timestamp(new Date().getTime()));
                    rolePers[i].setCreateTime(new Timestamp(new Date().getTime()));
                    dao.insert(rolePers[i]);
                }
            } catch (Exception e) {
                log.error("新增角色权限失败", e);
                throw e;
            }
        }
    }

    /**
     * 删除
     *
     * @param roleIds 角色IDs
     * @return
     */
    public void delete(String roleIds) throws Exception {
        if (roleIds != null) {
            try {
                Sql sql = Sqls.create("delete from sys_role_permission where role_id in (" + roleIds + ")");
                dao.execute(sql);
            } catch (Exception e) {
                log.error("删除角色权限异常", e);
                throw e;
            }
        }

    }
}
